package org.jeecg.modules.travel.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.modules.travel.dto.likes.AppLikePageDto;
import org.jeecg.modules.travel.dto.likes.LikeAddDto;
import org.jeecg.modules.travel.entity.JhAttraction;
import org.jeecg.modules.travel.entity.JhAttractionFile;
import org.jeecg.modules.travel.mapper.JhAttractionFileMapper;
import org.jeecg.modules.travel.mapper.JhAttractionMapper;
import org.jeecg.modules.travel.mapper.JhLikesMapper;
import org.jeecg.modules.travel.entity.JhLikes;
import org.jeecg.modules.travel.service.IJhLikesService;
import org.jeecg.modules.travel.util.AMapUtils;
import org.jeecg.modules.travel.vo.CompositeKey;
import org.jeecg.modules.travel.vo.attractionFile.AttractionFileVo;
import org.jeecg.modules.travel.vo.likes.AppLikeRecordVo;
import org.jeecg.modules.travel.vo.likes.PcLikesRecordVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 用户点赞表
 * @Author: jeecg-boot
 * @Date:   2025-04-19
 * @Version: V1.0
 */
@Service
public class JhLikesServiceImpl extends ServiceImpl<JhLikesMapper, JhLikes> implements IJhLikesService {

    @Resource
    private JhAttractionMapper attractionMapper;

    @Resource
    private JhAttractionFileMapper jhAttractionFileMapper;

    @Override
    public String giveThumbsUp(LikeAddDto dto) {
        JhAttraction attraction = attractionMapper.selectById(dto.getContentId());
        if(attraction == null) {
            return "景区未找到，请联系管理员";
        }
        JhLikes jhLikes = new JhLikes();
        jhLikes.setUserId(dto.getUserId());
        jhLikes.setContentType(dto.getContentType());
        jhLikes.setContentId(dto.getContentId());
        jhLikes.setLikeTime(new Date());
        boolean flag = save(jhLikes);
        if (flag && dto.getContentType().equals("0")) {
            int count = attraction.getLikeCount() + 1;
            UpdateWrapper<JhAttraction> wrapper = new UpdateWrapper<>();
            wrapper.lambda().eq(JhAttraction::getId, dto.getContentId())
                    .set(JhAttraction::getLikeCount,count);
            attractionMapper.update(null,wrapper);
        }
        return null;
    }

    @Override
    public IPage<AppLikeRecordVo> appPageList(AppLikePageDto dto,Page<JhLikes> page, QueryWrapper<JhLikes> queryWrapper) {
        IPage<AppLikeRecordVo> pageList = baseMapper.appPageList(page,queryWrapper);
        if (pageList.getRecords() != null && !pageList.getRecords().isEmpty()) {
            List<String> ids = pageList.getRecords().stream().filter(item -> item.getContentType().equals("0"))
                    .map(AppLikeRecordVo::getContentId).collect(Collectors.toList());
            List<JhAttraction> attractionList = attractionMapper.selectBatchIds(ids);
            Map<String,JhAttraction> attractionMap = attractionList.stream().collect(Collectors.toMap(JhAttraction::getId, i -> i));
            List<JhAttractionFile> list = jhAttractionFileMapper.selectList(new QueryWrapper<JhAttractionFile>()
                    .lambda().in(JhAttractionFile::getAttractionId,ids));
            Map<CompositeKey, List<AttractionFileVo>> fileMap = list.stream().collect(Collectors
                    .groupingBy(item -> new CompositeKey(item.getAttractionId(),item.getType()), Collectors.mapping(
                            i -> AttractionFileVo.builder().type(i.getType()).path(i.getPath()).build(),
                            Collectors.toList()
                    )));
            for (AppLikeRecordVo record : pageList.getRecords()) {
                if (attractionMap.get(record.getContentId()) != null) {
                    JhAttraction attraction = attractionMap.get(record.getContentId());
                    record.setAttractionName(attraction.getAttractionName());
                    record.setAttractionTheme(attraction.getAttractionTheme());
                    record.setAttractionDescription(attraction.getAttractionDescription());
                    record.setAttractionRecommendedDuration(attraction.getAttractionRecommendedDuration());
                    record.setAttractionCapacity(attraction.getAttractionCapacity());
                    record.setIsFeatured(attraction.getIsFeatured());
                    record.setAttractionHeat(attraction.getAttractionHeat());
                    record.setAttractionStatus(attraction.getAttractionStatus());
                    record.setBusinessHour(attraction.getBusinessHour());
                    record.setAttractionCountry(attraction.getAttractionCountry());
                    record.setAttractionProvince(attraction.getAttractionProvince());
                    record.setAttractionCity(attraction.getAttractionCity());
                    record.setAttractionDistrict(attraction.getAttractionDistrict());
                    record.setAreaCode(attraction.getAreaCode());
                    record.setAttractionAddress(attraction.getAttractionAddress());
                    record.setLongitude(attraction.getLongitude());
                    record.setLatitude(attraction.getLatitude());
                    record.setContactName(attraction.getContactName());
                    record.setContactPhone(attraction.getContactPhone());
                    record.setWebsite(attraction.getWebsite());
                    if (dto.getLon() != null && dto.getLat() != null) {
                        int distance = AMapUtils.getDistance(dto.getLon(), dto.getLat(), attraction.getLongitude(), attraction.getLatitude());
                        record.setDistance(BigDecimal.valueOf(distance).divide(new BigDecimal(1000),2, RoundingMode.HALF_UP));
                    }
                }
                List<AttractionFileVo> imgFile = fileMap.get(new CompositeKey(record.getId(), 0));
                List<AttractionFileVo> MpFile = fileMap.get(new CompositeKey(record.getId(), 1));
                List<AttractionFileVo> videoFile = fileMap.get(new CompositeKey(record.getId(), 2));
                record.setImgFile(imgFile == null ? new ArrayList<>() : imgFile);
                record.setMpFile(MpFile == null ? new ArrayList<>() : MpFile);
                record.setVideoFile(videoFile == null ? new ArrayList<>() : videoFile);
            }
        }
        return pageList;
    }

    @Override
    public String cancelLikes(String id) {
        JhLikes likes = getById(id);
        if (likes == null) {
            return "点赞记录未找到";
        }
        boolean flag = removeById(id);
        if (flag) {
            if (likes.getContentType().equals("0")) {
                long count = count(new QueryWrapper<JhLikes>().lambda().eq(JhLikes::getContentType, "0")
                        .eq(JhLikes::getContentId, likes.getContentId()));
                UpdateWrapper<JhAttraction> wrapper = new UpdateWrapper<>();
                wrapper.lambda().eq(JhAttraction::getId, likes.getContentId())
                        .set(JhAttraction::getLikeCount, count);
                attractionMapper.update(null, wrapper);
            }
            return null;
        }
        return "取消点赞失败!";
    }

    @Override
    public String cancelContent(String contentId, String type, String userId) {
        UpdateWrapper<JhLikes> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(JhLikes::getContentId, contentId)
                .eq(JhLikes::getContentType,type)
                .eq(JhLikes::getUserId,userId);
        boolean flag = remove(wrapper);
        if (flag) {
            if (type.equals("0")) {
                long count = count(new QueryWrapper<JhLikes>().lambda().eq(JhLikes::getContentType, "0")
                        .eq(JhLikes::getContentId, contentId));
                UpdateWrapper<JhAttraction> updateWrapper = new UpdateWrapper<>();
                updateWrapper.lambda().eq(JhAttraction::getId, contentId)
                        .set(JhAttraction::getLikeCount, count);
                attractionMapper.update(null, updateWrapper);
            }
            return null;
        }
        return "取消点赞失败!";
    }

    @Override
    public IPage<PcLikesRecordVo> queryPageList(Page<JhLikes> page, QueryWrapper<JhLikes> queryWrapper) {
        IPage<PcLikesRecordVo> pageList = baseMapper.queryPageList(page,queryWrapper);
        if (pageList.getRecords() != null && !pageList.getRecords().isEmpty()) {
            List<String> ids = pageList.getRecords().stream().filter(item -> item.getContentType().equals("0"))
                    .map(PcLikesRecordVo::getContentId).collect(Collectors.toList());
            List<JhAttraction> attractionList = attractionMapper.selectBatchIds(ids);
            Map<String,JhAttraction> attractionMap = attractionList.stream().collect(Collectors.toMap(JhAttraction::getId, i -> i));
            for (PcLikesRecordVo record : pageList.getRecords()) {
                if (attractionMap.get(record.getContentId()) != null) {
                    record.setContentName(attractionMap.get(record.getContentId()).getAttractionName());
                }
            }
        }
        return pageList;
    }

}
